import React, { Component } from 'react'

// 引入connect用于连接UI组件与redux
import { connect } from 'react-redux'

import { createIncrementAction, createDecrementAction, createIncrementAsyncAction } from '../../redux/actions/count'

class Count extends Component {
  state = {
    count: 0
  }

  increment = () => {
    const { value } = this.selectedNum
    this.props.add(Number(value))
  }

  decrement = () => {
    const { value } = this.selectedNum
    this.props.minus(Number(value))
  }

  // 奇数再加
  incrementWhenOdd = () => {
    const { value } = this.selectedNum

    if (this.props.count % 2 !== 0) {
      this.props.add(Number(value))
    }
  }

  incrementAsync = () => {
    const { value } = this.selectedNum
    this.props.addAsync(Number(value), 500)
  }

  render() {
    return (
      <div className="card w-30">
        <div className="card-body">
          <h5 className="card-title">Count组件</h5>
          <h6 className="card-subtitle">
            当前求和为：{this.props.count}，总人数为：{this.props.personCount}
          </h6>

          <div className="row mt-3">
            <div className="col-auto">
              <select className="form-select" ref={e => (this.selectedNum = e)}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
              </select>
            </div>
            <div className="col">
              <button className="btn btn-primary me-2" onClick={this.increment}>
                +
              </button>
              <button className="btn btn-primary me-2" onClick={this.decrement}>
                -
              </button>
              <button className="btn btn-primary me-2" onClick={this.incrementWhenOdd}>
                当前求和为奇数再加
              </button>
              <button className="btn btn-primary" onClick={this.incrementAsync}>
                异步加
              </button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

// 创建Count容器组件
export default connect(
  state => ({ count: state.count, personCount: state.persons.length }),
  /* 
   * mapDispatchToProps的一般写法
  dispatch => ({
    add: data => {
      // 通知redux执行加法
      dispatch(createIncrementAction(data))
    },
    minus: data => {
      dispatch(createDecrementAction(data))
    },
    addAsync: (data, interval) => {
      dispatch(createIncrementAsyncAction(data, interval))
    }
  })
   */

  // mapDispatchToProps的简写
  {
    add: createIncrementAction,
    minus: createDecrementAction,
    addAsync: createIncrementAsyncAction
  }
)(Count)
